<?php

namespace xing\privacyPhone\drive;

use xing\helper\resource\HttpHelper;
use xing\privacyPhone\core\PrivacyPhoneBase;
use xing\privacyPhone\core\PrivacyPhoneInterface;
use xing\privacyPhone\PrivacyPhoneMap;

class HuaWeiPrivacyPhone extends PrivacyPhoneBase implements PrivacyPhoneInterface
{
    public $domain = 'https://rtcpns.cn-north-1.myhuaweicloud.com/';

    public static function init($config = null)
    {
        $class = new static;
        $class->config = $config;
        return $class;
    }

    /**
     * @param $x
     * @param $caller
     * @param $callee
     * @param int $expireSecond
     * @return array
     * @throws \Exception
     */
    public function bindAxb($x, $caller, $callee, $expireSecond = 1800)
    {
        $post = [
            'relationNum' => $x,
            'callerNum' => $caller,
            'calleeNum' => $callee,
            'maxDuration' => $this->config['maxTime'] ?? 30
        ];
        if (!empty($expireSecond)) $post['duration'] = $expireSecond;
        HttpHelper::$method = 'POST';
        $result = json_decode($this->post('rest/caas/relationnumber/partners/v1.0', $post));
        switch ($result->resultcode) {
            case '1012010': // 已绑定过，请使用缓存技术或其他方式获取
                throw new \Exception('号码已绑被定过了', PrivacyPhoneMap::ERROR_ALREADY_BIND);
            case '1010002':
                throw new \Exception('拨号方和被拨号方的电话号码不能都一样');
            case '0':
                return [
                    'bindNumber' => $result->relationNum,
                    'serviceId' => $result->subscriptionId,
                    'expireTime' => $result->duration ? date('Y-m-d H:i:s', time() + $result->duration) : null,
                    'expireSecond' => $expireSecond
                ];
            default:
                throw new \Exception('获取号码失败，请检查:' . $result->resultdesc);
        }
    }

    public function delAxb($subscriptionId, $x = null)
    {

        $post = [
            'relationNum' => $x,
            'subscriptionId' => $subscriptionId,
        ];
        HttpHelper::$method = 'DELETE';
        $result = json_decode($this->post('rest/caas/relationnumber/partners/v1.0?' . http_build_query($post)));
        return $result->resultcode == 0;
    }

    public function post($path, $data = null)
    {
        $headers = [
            'Accept: application/json',
            'Content-Type: application/json;charset=UTF-8',
            'Authorization: WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
            'X-WSSE: ' . $this->buildWsseHeader($this->config['appKey'], $this->config['appSecret'])
        ];
        return $this->result = HttpHelper::post($this->domain . $path, $data ? json_encode($data) : null, $headers);
    }
    /**
     * 构建X-WSSE值
     *
     * @param string $appKey
     * @param string $appSecret
     * @return string
     */
    function buildWsseHeader($appKey, $appSecret) {
        $Created = date('Y-m-d\TH:i:s\Z'); //Created
        $nonce = uniqid(); //Nonce
        $base64 = base64_encode(hash('sha256', ($nonce . $Created . $appSecret), TRUE)); //PasswordDigest

        return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"", $appKey, $base64, $nonce, $Created);
    }
}
